package com.kyh.util;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * JsonUtil
 */
public class JsonUtil {


	/**
	 * @param obj
	 *            任意对象
	 * @return String
	 */
	public static String objectToJson(Object obj) {
		StringBuilder json = new StringBuilder();
		if (obj == null) {
			json.append("\"\"");
		} else if (obj instanceof String || obj instanceof Integer
				|| obj instanceof Float || obj instanceof Boolean
				|| obj instanceof Short || obj instanceof Double
				|| obj instanceof Long || obj instanceof BigDecimal
				|| obj instanceof BigInteger || obj instanceof Byte) {
			json.append("\"").append(stringToJson(obj.toString())).append("\"");
		} else if (obj instanceof Date) {
			(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(obj);
			json.append("\"").append(stringToJson(obj.toString())).append("\"");
		}

		else if (obj instanceof Object[]) {
			json.append(arrayToJson((Object[]) obj));
		} else if (obj instanceof List<?>) {
			json.append(listToJson((List<?>) obj));
		} else if (obj instanceof Map<?, ?>) {
			json.append(mapToJson((Map<?, ?>) obj));
		} else if (obj instanceof Set<?>) {
			json.append(setToJson((Set<?>) obj));
		} else {
			json.append(beanToJson(obj));
		}

		return json.toString();
	}

	/**
	 * @param bean
	 *            bean对象
	 * @return String
	 */
	public static String beanToJson(Object bean) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		PropertyDescriptor[] props = null;
		try {
			props = Introspector.getBeanInfo(bean.getClass(), Object.class)
					.getPropertyDescriptors();
		} catch (IntrospectionException e) {
		}
		if (props != null) {
			for (int i = 0; i < props.length; i++) {
				try {
					String name = objectToJson(props[i].getName());
					String value = objectToJson(props[i].getReadMethod()
							.invoke(bean));
					json.append(name);
					json.append(":");
					json.append(value);
					json.append(",");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * @param list
	 *            list对象
	 * @return String
	 */
	public static String listToJson(List<?> list) {
		StringBuilder json = new StringBuilder();
		if (list == null)
			return null;
		json.append("{\"results\":" + list.size() + ",\"rows\":");
		json.append("[");
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(objectToJson(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		json.append("}");
		return json.toString();
	}
	/**
	 * @param list
	 *            list对象
	 * @return String
	 */
	public static String listToJsonArray(List<?> list) {
		StringBuilder json = new StringBuilder();
		if (list == null)
			return null;
		json.append("[");
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(objectToJson(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}
	/**
	 * @param array
	 *            对象数组
	 * @return String
	 */
	public static String arrayToJson(Object[] array) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (array != null && array.length > 0) {
			for (Object obj : array) {
				json.append(objectToJson(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	/**
	 * @param map map对象
	 * @return String
	 */
	@SuppressWarnings("unchecked")
	public static String mapToJson(Map<?, ?> map) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (map != null && map.size() > 0) {
			for (Iterator<?> it = map.entrySet().iterator(); it.hasNext();) {
				Map.Entry<String, String> entry = (Map.Entry<String, String>)it.next();
	            String key = (String) entry.getKey();
				json.append(objectToJson(key));
				json.append(":");
				json.append(objectToJson(entry.getValue()));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * object转JSONObject（日期格式化）
	 * @param map map对象
	 * @return JSONObject
	 */
	public static JSONObject objToJSONObjectWithDateFormat(Object obj) {
		
		return JSON.parseObject(JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat));
	}

	/**
	 * object转JSONObject
	 * @param map map对象
	 * @return JSONObject
	 */
	public static JSONObject objToJSONObject(Object obj) {
		
		return JSON.parseObject(JSON.toJSONString(obj));
	}

	/**
	 * @param set
	 *            集合对象
	 * @return String
	 */
	public static String setToJson(Set<?> set) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (set != null && set.size() > 0) {
			for (Object obj : set) {
				json.append(objectToJson(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	/**
	 * @param s
	 *            参数
	 * @return String
	 */
	public static String stringToJson(String s) {
		if (s == null)
			return "";
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '/':
				sb.append("\\/");
				break;
			default:
				if (ch >= '\u0000' && ch <= '\u001F') {
					String ss = Integer.toHexString(ch);
					sb.append("\\u");
					for (int k = 0; k < 4 - ss.length(); k++) {
						sb.append('0');
					}
					sb.append(ss.toUpperCase());
				} else {
					sb.append(ch);
				}
			}
		}
		return sb.toString();
	}

	/**
	 * @param String
	 * @return map map对象
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> stringToMap(String str) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap = (Map<String, Object>) JSON.parse(str);
		return retMap;
	}
	
	public static <T> T parseToObj(String jsonStr, Class<T> clazz) {
		return JSON.parseObject(jsonStr, clazz);
	}

	public static String parseToString(Object obj) {
		return JSON.toJSONString(obj);
	}

	public static JSONObject copy(JSONObject sourceJO, JSONObject forcopyJO) {
		for (Map.Entry<String, Object> entry : forcopyJO.entrySet()) {
			
			if (sourceJO.containsKey(entry.getKey())) {
				continue;
			}
            sourceJO.put(entry.getKey(), entry.getValue());
        }
		return sourceJO;
	}

	/**
	 * 转成集合对象
	 * @param json
	 * @param type
	 * @param <T>
	 * @return
	 */
	public static <T> T fromJson(String json, TypeReference<T> type) {
		return JSON.parseObject(json, type);
	}
}